import gettext, json
import httplib2, urllib,  urllib2
import threading
import cookielib
from notify import notify
from configobj import ConfigObj
from gettext import gettext as _
gettext.textdomain('noc-client')
from netCheck import netCheck
from gi.repository import Gtk, GObject, Gst
from registerPort import registerOkitooPort

def do_login(email,passw):
    notify('Logging In','Please wait ....')
    values = {'email' : email,
             'pass' : passw,
             'function' : 'login' ,
             'controler' : 'user' ,
             'json' : 'yes' ,
                }
    headers = {"Connection":"close", "Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
    
    if Gtk.mainWindow.get_property('visible') == True:
    	loginWind = True
    else:
    	loginWind = False
    	
    if loginWind == True:
    	GObject.idle_add(Gtk.mainWindow.lbl_status.set_text, 'Connecting ...')
    	GObject.idle_add(Gtk.mainWindow.btn_login.set_sensitive,False)
    cj = cookielib.CookieJar()
    try:
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), urllib2.HTTPHandler())
    except :
    	pass

    url = 'http://nok.okitoo.net/ajax.php'

    data = urllib.urlencode(values)
    if loginWind == True:
    	GObject.idle_add(Gtk.mainWindow.lbl_status.set_text, 'Logging In ...')
    req = urllib2.Request(url, data, headers)

    f = opener.open(req)       

    response = urllib2.urlopen(req)

    the_page = response.read()
    headers = response.info()

    decoded = json.loads(the_page)

    login_result = decoded[0]["result"]
    if login_result == '0':
        if loginWind == True:
    		GObject.idle_add(Gtk.mainWindow.lbl_status.set_text, 'Wrong username of password')
    		GObject.idle_add(Gtk.mainWindow.btn_login.set_sensitive,True) 
    	else:
	    	Gtk.mainWindow.show()
	Gtk.tray.logout.hide()
        #message box with wrong username/password
        Gtk.is_logged = False
    if login_result == '1':
    	if loginWind == True:
	    	GObject.idle_add(Gtk.mainWindow.lbl_status.set_text, "Logged in !")   
                Gtk.mainWindow.hide()
                GObject.idle_add(Gtk.mainWindow.btn_login.set_sensitive,True) 
                config = ConfigObj('config.dat')
                config['email'] = email
                config['passw'] = passw
                config.write()
        Gtk.server = decoded[0]["server"]
#        global servers
        Gtk.servers = json.loads(decoded[0]["servers"])
        Gtk.session_id = ''
	Gtk.tray.logout.show()
        for cookie in cj:
            if cookie.name == 'PHPSESSID':
                Gtk.session_id = cookie.value
                Gtk.is_logged = True
                registerOkitooPort()
 
